/*
下载主程序
*/
package download

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"io"
	"monkeyCode/ftp/analyze"
	conn2 "monkeyCode/ftp/conn"
	"os"
	"sync"
	"time"
)

func copy(src, dst string) (int64, error) {
	sourceFileStat, err := os.Stat(src)
	if err != nil {
		return 0, err
	}

	if !sourceFileStat.Mode().IsRegular() {
		return 0, fmt.Errorf("%s is not a regular file", src)
	}

	source, err := os.Open(src)
	if err != nil {
		return 0, err
	}
	defer source.Close()

	destination, err := os.Create(dst)
	if err != nil {
		return 0, err
	}
	defer destination.Close()
	nBytes, err := io.Copy(destination, source)
	return nBytes, err
}

func FileExsist(path string)bool{
	lock := sync.RWMutex{}
	lock.Lock()
	defer lock.Unlock()
	f, err := os.Open(path)
	if err != nil {
		return false
	}
	defer f.Close()
	return true
}

func FileModifyTime(path string) (t time.Time){
	f, _ := os.Open(path)
	defer f.Close()
	fi, _ := f.Stat()
	return fi.ModTime()
}


func DownLoad(files chan *analyze.FtpFile){
	for v:= range files {
		var client = conn2.Connection()
		if client == nil {
			continue
		}
		size, _ := client.Size(v.Dir+"/"+v.FileName)
		if size > 0 {
			//不存在下载
			if !FileExsist(conn2.Conf.Dir +v.Time+"/"+v.FileName+".tmp"){
				logs.Info("开始下载 ",v.Dir,"  ", v.FileName)
				if err := client.DownloadResumeFile(v.Dir+"/"+v.FileName, conn2.Conf.Dir +v.Time+"/"+v.FileName+".tmp", false); err != nil {
					logs.Error("文件 %s, 下载错误 放入断点续传队列 ", v.FileName)
					fmt.Println(err)
					continue
				}
				if FileExsist(conn2.Conf.Dir +v.Time+"/release/"+v.FileName){
					continue
				}
				_,err := copy(conn2.Conf.Dir +v.Time+"/"+v.FileName+".tmp",conn2.Conf.Dir +v.Time+"/release/"+v.FileName)
				if err!=nil{
					logs.Error("文件 %s, 拷贝错误 %v", v.FileName,err)
					continue
				}
				logs.Info("检测到 %s下载成功",v.FileName)
			}else {
				//存在 并且last modify time > 10min
				mt :=FileModifyTime(conn2.Conf.Dir +v.Time+"/"+v.FileName+".tmp")
				mts := time.Now().Sub(mt).Minutes()
				if mts > 10 {
					logs.Info("续传下载 ",v.Dir,"  ", v.FileName)
					if err := client.DownloadResumeFile(v.Dir+"/"+v.FileName, conn2.Conf.Dir +v.Time+"/"+v.FileName+".tmp", false); err != nil {
						logs.Error("文件 %s, 下载错误 放入断点续传队列 ", v.FileName)
						fmt.Println(err)
						continue
					}
					if FileExsist(conn2.Conf.Dir +v.Time+"/release/"+v.FileName){
						continue
					}
					_,err := copy(conn2.Conf.Dir +v.Time+"/"+v.FileName+".tmp",conn2.Conf.Dir +v.Time+"/release/"+v.FileName)
					if err!=nil{
						logs.Error("文件 %s, 拷贝错误 %v", v.FileName,err)
						continue
					}
					logs.Info("检测到 %s下载成功",v.FileName)
				}
			}

		}
	}
}


